﻿using System;
using System.Net;
using GalaSoft.MvvmLight.Threading;
using Hammock;
using MyMeetup.Entities;
using Newtonsoft.Json;

namespace MyMeetup
{
    public class RequestHelper
    {
        public MeetupRequest Request { get; internal set; }
        public HttpStatusCode ExpectedStatusResult { get; internal set; }
        public RequestHelper(MeetupRequest request, HttpStatusCode expectedStatusResult)
        {
            Request = request;
            ExpectedStatusResult = expectedStatusResult;
        }

        public void BeginExecute(RestCallback callback, Action<RequestError> errorCallback)
        {
            DispatcherHelper.Initialize();
            DispatcherHelper.CheckBeginInvokeOnUI(() => GlobalLoading.Instance.IsLoading = true);

            Request.Client.BeginRequest(Request, (restRequest, restResponse, userState) =>
            {
                if (restResponse.StatusCode != ExpectedStatusResult)
                {
                    RequestError error;
                    if (!string.IsNullOrEmpty(restResponse.Content))
                    {
                        error = JsonConvert.DeserializeObject<RequestError>(restResponse.Content);
                    }
                    else
                    {
                        error = new RequestError() { details = "There was a problem connecting to meetup.com", problem = "Unknown Error" };
                    }

                    errorCallback(error);
                }
                else
                {
                    callback(restRequest, restResponse, userState);
                }
            });
        }
    }
}
